﻿using System;
using System.Collections.Generic;
using BFlatCompile.Nodes;

namespace BFlatCompile.Serializer
{
	internal static class Phase26FindSystemExceptionClassId
	{
		public static string Do(Compiler compiler, Class[] classes, Dictionary<string, int> startLocations)
		{
			List<string> output = new List<string>();
			Class systemException = GetSystemExceptionClass(classes);
			Method method = (Method)systemException.GetMember("_IRE", false);
			string signature = "M" + method.ID;

			int systemExceptionId = systemException.ID;
			int invokeRuntimeExceptionStartLoc = startLocations[signature];

			if (compiler.IsReadable)
			{
				return "System.Exception Class ID#: " + systemExceptionId + "\n" +
					"Invoke runtime exception method start location: " + invokeRuntimeExceptionStartLoc;
			}
			else
			{
				foreach (int num in new int[] { systemExceptionId, invokeRuntimeExceptionStartLoc })
				{
					output.Add(Util.ToHex(compiler, num));
				}

				return string.Join("`", output);
			}
		}

		private static Class GetSystemExceptionClass(Class[] classes)
		{
			foreach (Class c in classes)
			{
				if (c.FullName == "System.Exception")
				{
					return c;
				}
			}
			throw new Exception("System.Exception was not found. This should never happen.");
		}
	}
}
